"""
    数据库操作
"""
import json

import pymysql

from zonghe.caw import file_reader


def connect(db_info):
    """
    建立数据库链接
    :param db_info: 数据库的信息
    :return: 数据库链接
    """
    try:
        r = pymysql.connect(
            user=db_info["user"],
            password=db_info["pwd"],
            host=db_info["host"],
            port=db_info["port"],
            database=db_info["name"],
            charset='utf8'
        )
        print("链接数据库成功")
        return r
    except Exception as e:
        print("链接数据库异常", e)


def dis_connect(conn):
    """
    断开链接
    :param conn: 要断开的链接
    :return:
    """
    try:
        conn.close()
        print("断开数据库链接成功")
    except Exception as e:
        print("断开数据库链接异常", e)


def execute(conn, sql):
    """
    执行sql语句
    :param conn: 数据库链接
    :param sql: sql语句
    :return:
    """
    try:
        cursor = conn.cursor()  # 在链接上获取游标
        cursor.execute(sql)  # 在游标上执行sql
        conn.commit()  # 在连接上提交
        r = cursor.fetchall()  # 获取全部数据
        print("执行SQL语句", sql, "成功")
        return r
    except Exception as e:
        print("执行SQL语句", sql, "失败，异常信息为", e)


if __name__ == '__main__':
    db_info = json.loads(file_reader.read_config("db_info"))
    r = connect(db_info)
    ret = execute(r, "delete from member where MobilePhone = '18012345671'")
    ret = execute(r, "select * from member where MobilePhone = '18012345671'")
    print(ret)
    dis_connect(r)
